import { constantRoutes } from '@/router'
import http from '@/utils/request'
import Layout from '@/layout'

/**
 * 遍历后台传来的路由字符串，转换为组件对象
 * @param {*} asyncRouterMap
 */
function filterAsyncRouter(asyncRouterMap) {
  return asyncRouterMap.filter(route => {
    if (route.component) {
      // Layout组件特殊处理
      if (route.component === 'Layout') {
        route.component = Layout
      } else {
        route.component = loadView(route.component)
        /* route.component = { // 路由懒加载
          return () => import(`@/views/${view}`)
        } */
      }
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children)
    }
    return true
  })
}

export const loadView = (view) => { // 路由懒加载
  return () => import(`@/views/${view}`)
}

/**
 *  使用meta.role，以确定当前用户是否具有权限
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * 通过递归过滤异步路由表
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []
  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  isLoad: false, // 路由加载状态标记（false：未加载，true：已加载）
  addRoutes: []
}

const mutations = {
  SET_IS_LOAD: (state, status) => {
    state.isLoad = status
  },
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  // 生成路由
  generateRoutes({ commit }) {
    return new Promise(resolve => {
      http({
        url: '/sys/currentUser/menus',
        method: 'get'
      }).then(res => {
        const accessedRoutes = filterAsyncRouter(res.data)
        commit('SET_ROUTES', accessedRoutes)
        resolve(accessedRoutes)
        commit('SET_IS_LOAD', true)
      })
    })
  },
  // 改变路由加载状态标记
  changeIsLoad({ commit, status }) {
    commit('SET_IS_LOAD', status)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
